<?php

namespace App\Http\Controllers\Home;

use App\Models\Home\UserInfo;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Session;

class FansController extends Controller
{
    //显示粉丝列表
    public function index($user_id)
    {
        //取出用户信息
        $info = UserInfo::where('user_id', $user_id)->first();
        //获取我的关注列表
        $follows = UserInfo::where('user_id', Session::get('user.id'))->first()->following;
        $follows = explode(',', $follows);
        //取出该用户的粉丝id列表，字符串格式
        $fans = UserInfo::where('user_id', $user_id)
            ->get()->first()->fans;
        //如果该用户还没有粉丝
        if(!$fans){
            return view('home.profile', ['info' => $info, 'follows' => $follows])->with('fansfails', '暂时没有粉丝');
        }else{
            //将粉丝列表转数组
            $fans_array = explode(',', $fans);
            //遍历出每个粉丝的用户信息
            $fan = array();
            foreach($fans_array as $fans_id)
            {
                $fan[] = UserInfo::where('user_id', $fans_id)->get()->first();
            }
            return view('home.profile', ['info' => $info, 'follows' => $follows, 'fans' => $fan]);
        }
    }

    //移除粉丝
    public function destroy($user_id, $fans_id)
    {
        //将该用户id从本用户fans字段中删除
        //取出本用户粉丝的id列表
        $fans = UserInfo::where('user_id', $user_id)->get()->first()->fans;
        //转数组
        $fans_array = explode(',', $fans);
        //该用户id在数组中的位置
        $key = array_search($fans_id, $fans_array);
        //从数组中删除该用户id
        array_splice($fans_array, $key, 1);
        //转字符串
        $fans = implode(',', $fans_array);
        //更新本用户的fans字段
        UserInfo::where('user_id', $user_id)->update(['fans' => $fans]);

        //将本用户id从该用户following字段中删除
        //取出该用户following列表
        $following = UserInfo::where('user_id', $fans_id)->get()->first()->following;
        //转数组
        $following_array = explode(',', $following);
        //本用户id在数组中的位置
        $key = array_search($user_id, $following_array);
        //从数组中删除本用户id
        array_splice($following_array, $key, 1);
        //转字符串
        $following = implode(',', $following_array);
        //更新该粉丝的following字段
        UserInfo::where('user_id', $fans_id)->update(['following' => $following]);
    }

}
